//
//  MyTravelAppDelegate.m
//  MyTravel
//
//  Created by Hunk on 11-5-25.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "MyTravelAppDelegate.h"
#import "NewsViewController.h"
#import "VisaViewController.h"
#import "AboutViewController.h"
#import "NetworkManager.h"
#import "MyLoadingView.h"
#import "NSString+URLEncoding.h"


@implementation MyTravelAppDelegate


@synthesize window=_window;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{   
    // Init tabBarController
    tabBarController = [[UITabBarController alloc] init];
    
    // NewsViewController
    NewsViewController* newsViewController = [NewsViewController alloc];
    newsViewController.title = @"最新线路";
    [newsViewController.tabBarItem setImage:[UIImage imageNamed:@"news.png"]];    
    UINavigationController* newsNavigationController = [[UINavigationController alloc] initWithRootViewController:newsViewController];
    [newsViewController release];
    newsNavigationController.navigationBar.tintColor = TINTCOLOR;
    
    // VisaViewController
    VisaViewController* visaViewController = [VisaViewController alloc];
    visaViewController.title = @"签证服务";
    [visaViewController.tabBarItem setImage:[UIImage imageNamed:@"visa.png"]];
    UINavigationController* visaNavigationController = [[UINavigationController alloc] initWithRootViewController:visaViewController];
    [visaViewController release];
    visaNavigationController.navigationBar.tintColor = TINTCOLOR;
    
    // About
    AboutViewController* aboutViewController = [[AboutViewController alloc] initWithStyle:UITableViewStyleGrouped];
    aboutViewController.title = @"关于";
    [aboutViewController.tabBarItem setImage:[UIImage imageNamed:@"about.png"]];
    UINavigationController* aboutNavigationController = [[UINavigationController alloc] initWithRootViewController:aboutViewController];
    [aboutViewController release];
    aboutNavigationController.navigationBar.tintColor = TINTCOLOR;
    
    // Set tabBar view controllers
    [tabBarController setViewControllers:[NSArray arrayWithObjects:
                                          newsNavigationController,
                                          visaNavigationController,
                                          aboutNavigationController, nil]];
    
    [newsNavigationController release];
    [visaNavigationController release];
    [aboutNavigationController release];
    
    // For APNs
    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:
     UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert];
    
    [self.window makeKeyAndVisible];
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    /*
     Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
     Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
     */
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    /*
     Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
     If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
     */
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    /*
     Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
     */
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Application icon badge number
    if(0 != application.applicationIconBadgeNumber)
    {
        application.applicationIconBadgeNumber = 0;
    }
    
    static int ntimer = 1;
    
    if(ntimer == 1)
    {   
        ntimer = 2;
        
        [[MyLoadingView sharedMyLoadingView] startLoadingAnimationWithName:@"版本验证中"
                                                           backgroundImage:@"Default.png"];
    }
    
    NSDictionary* parameters =[NSDictionary dictionaryWithObjectsAndKeys:
                               [[[UIDevice currentDevice] name] URLEncodedString], @"name",
                               [[[UIDevice currentDevice] model] URLEncodedString], @"model",
                               [[[UIDevice currentDevice] localizedModel] URLEncodedString], @"localizedModel",
                               [[[UIDevice currentDevice] systemName] URLEncodedString], @"systemName", 
                               [[[UIDevice currentDevice] systemVersion] URLEncodedString], @"systemVersion",
                               [[[UIDevice currentDevice] uniqueIdentifier] URLEncodedString], @"uniqueIdentifier", nil];
    
    [[NetworkManager sharedNetworkManager] requestServerForMethod:NetworkRequest_GetAppVersion
                                                   WithParameters:parameters
                                                 AndCallBackScope:self
                                                    AndSuccessSel:@"onSuccess:" 
                                                     AndFailedSel:@"onSuccess:"];
}

- (void)onSuccess:(id)sender
{
    NSDictionary* resultDic = (NSDictionary*)sender;
    
    if([[resultDic objectForKey:@"appVersion"] floatValue] > VERSION_APP)
    {
        UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:@"请下载最新版应用程序"
                                                            message:[resultDic objectForKey:@"updateURL"]
                                                           delegate:self
                                                  cancelButtonTitle:nil
                                                  otherButtonTitles:@"好的", nil];
        [alertView show];
        [alertView release];
    }
    else
    {
        if(![[self.window subviews] containsObject:tabBarController.view])
        {
            [self.window addSubview:tabBarController.view];
        }
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex;
{   
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:alertView.message]];
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    /*
     Called when the application is about to terminate.
     Save data if appropriate.
     See also applicationDidEnterBackground:.
     */
}

#pragma mark -
#pragma mark Apple Push Notification Server
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    NSString* deviceTokenString = [[deviceToken description] stringByReplacingOccurrencesOfString:@"<" withString:@""];
    deviceTokenString = [deviceTokenString stringByReplacingOccurrencesOfString:@">" withString:@""];
    
    NSDictionary* parameters =[NSDictionary dictionaryWithObjectsAndKeys:
                               [[[UIDevice currentDevice] uniqueIdentifier] URLEncodedString], @"uniqueIdentifier", 
                               [deviceTokenString URLEncodedString], @"deviceToken", nil];
    
    [[NetworkManager sharedNetworkManager] requestServerForMethod:NetworkRequest_CacheDeviceToken
                                                   WithParameters:parameters
                                                 AndCallBackScope:self
                                                    AndSuccessSel:@"onSuccessForCacheDeviceToken:" 
                                                     AndFailedSel:@"onFailedForCacheDeviceToken:"];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{   
    if ( application.applicationState == UIApplicationStateActive )
    {
        // 一直在前台状态
        for(id key in userInfo)
        {
            if ([[userInfo objectForKey:key] objectForKey:@"alert"]) 
            {   
                NSString* alertTitle = @"推送通知";
                UIAlertView* alert = [[UIAlertView alloc] initWithTitle:alertTitle
                                                                message:[[userInfo objectForKey:@"aps"] objectForKey:@"alert"]
                                                               delegate:self
                                                      cancelButtonTitle:@"好的"
                                                      otherButtonTitles:nil];
                [alert show];
                [alert release];
            }
        }
    }
    else
    {
        application.applicationIconBadgeNumber = 0;
    }
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
    NSLog(@"ERROR=%@\n", error);
}

#pragma mark -
#pragma mark Call back ForCacheDeviceToken
- (void)onSuccessForCacheDeviceToken:(id)sender
{
    NSLog(@"SUCESS:%@", (NSDictionary*)sender);
}
- (void)onFailedForCacheDeviceToken:(id)sender
{
    NSLog(@"FAILED%@", (NSDictionary*)sender);
}

- (void)dealloc
{
    SAFE_RELEASE(tabBarController)
    
    [_window release];
    [super dealloc];
}

@end
